import PAGE from '../../../utils/middleware/page'
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import store from '../../../store/index'
const app = getApp()
Page(PAGE({
    behaviors: [storeBindingsBehavior],
    storeBindings: {
        store,
        fields: {
            needRefresh: 'vehicle.needRefresh'
        },
        actions: {
            updateNeedRefresh: 'vehicle.updateNeedRefresh'
        }
    },
    data: {
        info: {},
        apiField: {
            module: 'scanParking',
            api: 'Scan',
            data: 'info',
            search: {
                parkId: null,
            }
        },
        options: {
            parkId: null,
            devicePort: null,
            doorPort: null,
            direction: null
        },
        isLogin: app.globalData.isLogin
    },
    async onLoad(options) {
        this.handleQrcodeParams(options)
        // if (this.data.isLogin) {
        //     this.fetchData()
        // } else {
        //     this.data.wxLoginRes = await wx.$Fun.wxLogin()
        //     this.login()
        // }
        this.data.wxLoginRes = await wx.$Fun.wxLogin()
        this.login()
    },
    onPullDownRefresh() {
        this.fetchData();
        wx.stopPullDownRefresh();
    },
    handleQrcodeParams(options) {
        if (options.q) {
            var scene = decodeURIComponent(options.q)
            var params = scene.split('?')[1]

            this.setData({
                'options.parkId': wx.$util.getUrlParams('parkId', params),
                'options.devicePort': wx.$util.getUrlParams('devicePort', params),
                'options.doorPort': wx.$util.getUrlParams('doorPort', params),
                'options.direction': wx.$util.getUrlParams('direction', params),
            })
        } else {
            // this.setData({
            //     'options.parkId': 300241572614277,
            //     'options.devicePort': 1,
            //     'options.doorPort': 1,
            //     'options.direction': 1,
            // })
            wx.$Fun.showToast("扫码参数错误")
        }
    },
    async fetchData() {
        this.data.apiField.search.parkId = this.data.options.parkId
        this.handleFetchData({})
    },
    //快捷登录
    async login() {
        var _this = this
        try {
            const res = await wx.$Api.member.Login({
                data: {
                    Code: this.data.wxLoginRes.code
                }
            })
            if (res.Data.Status == 0) {
                this.setData({
                    showGetPhone: true
                })
            }
            else {
                //获取token
                this.getToken(res.Data.Token, () => {
                    _this.fetchData()
                })
            }
        }
        catch (e) {
            wx.$Fun.showToast(e.Message)
        }
        finally {
            this.data.wxLoginRes = await wx.$Fun.wxLogin()
        }
    },
    // 注册前先解密手机
    async register(event) {
        if (event.detail.errMsg !== 'getPhoneNumber:ok') return
        var _this = this
        try {
            var request = {
                WxCode: this.data.wxLoginRes.code,
                IV: event.detail.iv,
                EncryptedData: event.detail.encryptedData
            }
            const res = await wx.$Api.member.Register({ data: request })
            //获取token
            this.getToken(res.Data.Token, () => {
                _this.fetchData()
            })
        } catch (e) {
            wx.$Fun.showToast(e.Message)
        }
        finally {
            this.data.wxLoginRes = await wx.$Fun.wxLogin()
        }
    },
    getToken(token, cb) {
        var _this = this
        wx.setStorage({
            key: 'token',
            data: `bearer ${token.AccessToken}`,
            success() {
                app.globalData.isLogin = true
                _this.updateNeedRefresh(true)
                _this.setData({
                    showGetPhone: false,
                    isLogin: true
                })
                typeof cb === 'function' && cb()
            }
        })
    },
    handlePhoneCall(e) {
        var phone = e.currentTarget.dataset.phone
        wx.makePhoneCall({
            phoneNumber: phone
        })
    },
    async handlePay(e) {
        try {
            var req = {
                ParkId: this.data.options.parkId,
                DevicePort: this.data.options.devicePort,
                DoorPort: this.data.options.doorPort,
                Direction: this.data.options.direction,
                PayMethod: 1
            }
            const res = await wx.$Api.scanParking.Pay({ data: req })

            //请求支付参数
            const prePayRes = await wx.$Api.payment.PrePay({ data: { tradeNo: res.Data } })
            wx.$Fun.wxPay(prePayRes.Data)
                .then(resp => {
                    this.fetchData()
                }).catch(e => {
                    console.log(e)
                })
        } catch (e) {
            wx.$Fun.showToast(e.Message)
        }
    },
    async handleOpenDoor() {
        var _this = this
        wx.showModal({
            title: '提示',
            content: '点击确定开门，减1次开门次数，确定要开门吗？',
            success: async function (showRes) {
                if (showRes.confirm) {
                    _this.openDoor()
                }
            }
        })
    },
    async openDoor() {
        try {
            await wx.$Api.scanParking.OpenDoor({
                data: {
                    OrderId: this.data.info.Order.Id,
                    DevicePort: this.data.options.devicePort,
                    DoorPort: this.data.options.doorPort,
                    Direction: this.data.options.direction,
                }
            })
            wx.$Fun.showToast('开门成功')
            this.fetchData()
        }
        catch (e) {
            wx.$Fun.showToast(e.Message)
        }
    },
    async handleComplete() {
        var _this = this
        wx.showModal({
            title: '提示',
            content: '点击确定开门并结束停车，确定要离场吗？',
            success: async function (showRes) {
                if (showRes.confirm) {
                    _this.complete()
                }
            }
        })
    },
    async complete() {
        try {
            await wx.$Api.scanParking.Complete({
                data: {
                    OrderId: this.data.info.Order.Id,
                    DevicePort: this.data.options.devicePort,
                    DoorPort: this.data.options.doorPort,
                    Direction: this.data.options.direction,
                }
            })
            wx.$Fun.showToast('结算成功')
            this.fetchData()
        }
        catch (e) {
            wx.$Fun.showToast(e.Message)
        }
    },
    handlePhoneCall(e) {
        var phone = e.currentTarget.dataset.phone
        wx.makePhoneCall({
            phoneNumber: phone
        })
    },
}))